package cn.lee.cplibrary.util.takephotos;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.util.List;

import cn.lee.cplibrary.R;
import cn.lee.cplibrary.constant.CpConfig;
import cn.lee.cplibrary.init.CPInitializer;
import cn.lee.cplibrary.util.LogUtil;
import cn.lee.cplibrary.util.ObjectUtils;
import cn.lee.cplibrary.util.ToastUtil;
import cn.lee.cplibrary.widget.dialog.CpComDialog;
import cn.lee.cplibrary.util.system.AppUtils;

/**
 * 获取拍照或者相册中的图片,需要外部子类配合PermissionX并实现请求权限后,相应功能可以可使用,具体使用方法参考CPDemo
 */
public abstract class PhotoAUtil {
    public static boolean onlyUseSystemCamera = true;//调用相机拍照时候：是否只使用系统相机
    public static File tempFile;
    //请求相机
    public static final int REQUEST_CAPTURE = 300;
    //请求相册
    public static final int REQUEST_PICK = 301;

    @ColorInt
    public static int colorAlbum = Color.parseColor("#000000"), colorgraph = Color.parseColor("#000000"), colorCancel = Color.parseColor("#999999");
    @DrawableRes
    public static int bgAlbum = R.drawable.cp_photo_bgt10_selector, bggraph = R.drawable.cp_photo_bgb10_selector, bgCancel = R.drawable.cp_photo_bg10_selector;

    public PhotoAUtil() {
        checkPermit();
    }

    private static void checkPermit() {
        CPInitializer.checkInitialization();
    }

    /**
     * 注意：拍照前，Activity的OnCreate方法中必须调用此方法初始化文件临时缓存路径
     *
     * @param activity
     * @param savedInstanceState
     */
    public static void init(Activity activity, Bundle savedInstanceState) {
        createCameraTempFile(activity, savedInstanceState);
    }

    /**
     * 创建调用系统照相机待存储的临时文件
     */
    public static void createCameraTempFile(Context context, Bundle savedInstanceState) {
        checkPermit();
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
//            tempFile = new File(checkDirPath( Environment.getExternalStorageDirectory().getPath()+ "/image/"),
//                    System.currentTimeMillis() + ".jpg");
            tempFile = new File(checkDirPath(new CpConfig(context).getImgCachePath()), System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 检查文件是否存在
     */
    public static String checkDirPath(String dirPath) {
        checkPermit();
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    private static Dialog picDialog;


    /**
     * 注意：打开上传图片的Dialog 必须重写onActivityResult
     *
     * @param activity 一定不能为空
     * @param fragment 不为null表示在Fragment中上传图片且activity是fragment挂载的Activity ，是null表示在Activity中上传图片
     * @return
     */
    public Dialog showPicChooseDialog(final AppCompatActivity activity, final Fragment fragment) {
//        if (picDialog == null) {
        View view = LayoutInflater.from(activity).inflate(R.layout.cp_dialog_pic_choose, null);
        picDialog = CpComDialog.getBottomDialog(activity, true, view);
        if (picDialog == null) {
            return null;
        }
        TextView photoAlbum = view.findViewById(R.id.photoAlbum);
        TextView photograph = view.findViewById(R.id.photograph);
        TextView cancel = view.findViewById(R.id.cancel);
        photoAlbum.setTextColor(colorAlbum);
        photograph.setTextColor(colorgraph);
        cancel.setTextColor(colorCancel);
        photoAlbum.setBackgroundResource(bgAlbum);
        photograph.setBackgroundResource(bggraph);
        cancel.setBackgroundResource(bgCancel);
        //相册
        photoAlbum.setOnClickListener(arg0 -> {
            picDialog.dismiss();
            goForAlbum(activity, fragment);
        });
        //照相
        photograph.setOnClickListener(arg0 -> {
            picDialog.dismiss();
            goForCamera(activity, fragment);
        });

        cancel.setOnClickListener(v -> picDialog.dismiss());
//        } else {
//
//            picDialog.show();
//        }
        return picDialog;
    }

    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePathFromUri(Context context, final Uri uri) {
        checkPermit();
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * @param context
     * @param requestCode
     * @param resultCode
     * @param data
     * @return
     */
    public static File getImageFile(Context context, int requestCode, int resultCode, Intent data) {
        return getImageFile(context, requestCode, resultCode, data, "temp");
    }

    /**
     * 打开相机
     * FileProvider 从安卓4.4开始使用 Build.VERSION_CODES.KITKAT
     * 动态申请权限从安卓6.0开始使用 Build.VERSION_CODES.M
     */
    public void goForCamera(AppCompatActivity activity, Fragment fragment) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            onlyUseSysCamera(intent, activity);//设置只使用系统相机
            Uri imgUri = FileProvider.getUriForFile(activity, AppUtils.getAppId(activity) + ".provider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            if (fragment == null) {
                activity.startActivityForResult(intent, REQUEST_CAPTURE);
            } else {
                fragment.startActivityForResult(intent, REQUEST_CAPTURE);
            }
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            onlyUseSysCamera(intent, activity);//设置只使用系统相机
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            if (fragment == null) {
                activity.startActivityForResult(intent, REQUEST_CAPTURE);
            } else {
                fragment.startActivityForResult(intent, REQUEST_CAPTURE);
            }
        }
    }

    public void goForAlbum(AppCompatActivity activity, Fragment fragment) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (fragment == null) {
            activity.startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
        } else {
            fragment.startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
        }
    }


    /**
     * @param imgName 文件名( 格式是.jpg,是在本方法中追加的)
     * @return
     */
    public static File getImageFile(Context context, int requestCode, int resultCode, Intent data, String imgName) {
        checkPermit();
        File file = null;
        if (resultCode != Activity.RESULT_OK) {
            return null;
        }
        Uri uri = null;
        switch (requestCode) {
            case PhotoAUtil.REQUEST_CAPTURE:
                uri = Uri.fromFile(tempFile);
                break;
            case PhotoAUtil.REQUEST_PICK:  //调用系统相册返回
                if (data != null) {
                    uri = data.getData();
                }
                break;
        }
        if (uri != null) {
            String filePath = PhotoAUtil.getRealFilePathFromUri(context, uri);//图片的路径
            LogUtil.i("", "原图路径=" + filePath);
            if (ObjectUtils.isEmpty(filePath)) {//相册中存在尚未下载的预览图，这类图片图片路径是空的
                ToastUtil.showToast(context, "图片路径不正确，换张图试试");
                return null;
            } else {
                String fileName = ImageUtils.getFileName(context, filePath, imgName + ".jpg");
                file = new File(fileName);
                LogUtil.i("", "压缩路径=" + fileName);
            }
        }

        return file;
    }


    // 对使用系统拍照的处理
    public String getCameraPhoneAppInfos(Context context) {
        try {
            String strCamera = "";
            List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
            for (int i = 0; i < packages.size(); i++) {
                try {
                    PackageInfo packageInfo = packages.get(i);
                    String strLabel = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
                    // 一般手机系统中拍照软件的名字 可能尚未找全 需要持续添加适配
                    if ("相机,照相机,照相,拍照,摄像,Camera,camera".contains(strLabel)) {
                        strCamera = packageInfo.packageName;
                        if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (strCamera != null) {
                return strCamera;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 打开相机时，如果满足以下2个条件，则只打开系统相机
     * （1） onlyUseSystemCamera=true，
     * （2）获取手机系统相机包名成功
     * 只打开系统相机做法：将包名设置给打开相机的Intent
     *
     * @param intent 打开相机的 Intent
     */
    public void onlyUseSysCamera(Intent intent, Context activity) {
        if (!isOnlyUseSystemCamera()) {
            return;
        }
        try { //尽可能调用系统相机
            String cameraPackageName = getCameraPhoneAppInfos(activity);
            if (cameraPackageName == null) {
                cameraPackageName = "com.android.camera";
            }
            final Intent intent_camera = activity.getPackageManager().getLaunchIntentForPackage(cameraPackageName);

            if (intent_camera != null) {
                intent.setPackage(cameraPackageName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static float getDesWidth() {
        return ImageUtils.getDesWidth();
    }

    /**
     * 设置压缩后宽高
     *
     * @param desWidth
     */
    public static void setDesWidth(float desWidth) {
        ImageUtils.setDesWidth(desWidth);
    }

    /**
     * 设置质量
     *
     * @param quality
     */
    public static void setQuality(int quality) {
        ImageUtils.setQuality(quality);
    }

    public static int getQuality() {
        return ImageUtils.getQuality();
    }


    public boolean isOnlyUseSystemCamera() {
        return onlyUseSystemCamera;
    }

    public static void setOnlyUseSystemCamera(boolean onlyUseSystemCamera) {
        PhotoAUtil.onlyUseSystemCamera = onlyUseSystemCamera;
    }
}